# -*- coding: utf-8 -*-
from openerp.osv import fields
from openerp.osv import osv
from openerp import SUPERUSER_ID
import datetime, time
import openerp.addons.decimal_precision as dp
from openerp.tools import DEFAULT_SERVER_DATETIME_FORMAT, float_compare, float_is_zero
from openerp.http import request
from dateutil.relativedelta import relativedelta
ISODATEFORMAT = '%Y-%m-%d'
ISODATETIMEFORMAT = "%Y-%m-%d %H:%M:%S"
type_dict = dict([('changeworkday', u'调休'), ('overtime', u'加班'), ('annual_leave', u'年假')])
type_http = dict([('changeworkday', 'leave'), ('overtime', 'work')])
class work_overtime_leave(osv.osv):
    _name = 'work.overtime.leave'
    _rec_name = 'user_id'

    def name_search(self, cr, uid, name, args=None, operator='ilike', context=None, limit=100):
        if context.get('reconcile_ids') == 'select':
            date_now = time.strftime('%Y-%m-%d', time.localtime(time.time()))
            args.extend(['|', ['expire_date', '=', False], ['expire_date', '>=', date_now]])
            leave_ids = self.search(cr, uid, args + [('name', operator, name)] if name else args, limit=limit, context=context)
            return self.name_get(cr, uid, leave_ids, context=context)
        else:
            return super(work_overtime_leave, self).name_search(cr, uid, args, operator=operator,
                                                            context=context, limit=limit)

    def _compute_residue_qty(self, cr, uid, ids, name, args, context=None):
        """计算字段： 计算出未核销的时间"""
        res = {}
        reconcile_obj = self.pool.get('work.time.reconcile')
        for leave_row in self.browse(cr, uid, ids, context=context):
            reconcile_ids = reconcile_obj.search(cr, uid, [('ol_id', '=', leave_row.id),
                                                           ('reconcile_id', '=', False)], context=context)
            res[leave_row.id] = sum([reconcile_row.hour_qty for reconcile_row in
                                     reconcile_obj.browse(cr, uid, reconcile_ids, context=context)])
        return res

    def fields_view_get(self, cr, uid, view_id=None, view_type='form', context=None, toolbar=False, submenu=False):
        """当 除了管理员，其他在系统中没有员工资料的用户，不能查看 打卡调休记录"""
        res = super(work_overtime_leave, self).fields_view_get(
            cr, uid, view_id=view_id, view_type=view_type, context=context, toolbar=toolbar, submenu=False)
        employee_obj = self.pool.get('hr.employee')
        employee_id = employee_obj.search(cr, uid, [
            ('user_id', '=', uid)], context=context)
        user_obj = self.pool.get('res.users')
        if not employee_id and not user_obj.has_group(cr, uid, 'base.group_erp_manager'):
            raise osv.except_osv(u'错误', u"您在系统里面没有对应的员工!")
        return res

    def get_approve_user_id(self, cr, uid, user_id, context=None):
        """获取员工的部门经理，以此作为加班／调休的审批人"""
        res = {}
        employee_obj = self.pool.get('hr.employee')
        employee_id = employee_obj.search(cr, uid, [
            ('user_id', '=', user_id)], context=context)
        if employee_id:
            employee_row = employee_obj.browse(cr, uid, employee_id[0], context=context)
            res.update({'employee_id': employee_id[0],
                        'approver_user_id': employee_row.parent_id and
                                            employee_row.parent_id.user_id and
                                            employee_row.parent_id.user_id.id or False})

        return res


    def default_get(self, cr, uid, fields, context=None):
        """获取默认值（本次获取的是 用户的）"""
        res = super(work_overtime_leave, self).default_get(
            cr, uid, fields, context=context)
        res.update(self.get_approve_user_id(cr, uid, res.get('user_id'), context=context))
        return res

    def _get_leave_work_ids(self, cr, uid, ids, context=None):
        """获取用户调休可用的 时间记录"""
        overtime_leave_ids = []
        for reconcile_row in self.browse(cr, uid, ids, context=context):
            overtime_leave_ids.append(reconcile_row.ol_id.id)
        return overtime_leave_ids

    def _residue_fnct_search(self, cr, user, obj, name, args, context=None):
        """function search 核销记录必须要设置，不然没法搜索"""
        cr.execute("""SELECT leave.id as id,sum(reconcile.hour_qty) as hour_qty FROM work_overtime_leave AS leave
                      LEFT JOIN work_time_reconcile AS reconcile  ON reconcile.ol_id=leave.id
                      WHERE reconcile.reconcile_id IS NULL AND leave.type in ('overtime', 'annual_leave')
                      GROUP BY leave.id""")
        res = dict(cr.fetchall())
        if args[0] in [('residue_qty', '!=', 0), ('residue_qty', '>', 0)]:
            operator = 'in'
        else:
            operator = 'not in'
        return [('id', operator, [id for id, hour_qty in res.iteritems() if hour_qty > 0])]

    def onchange_start_end_time(self, cr, uid, ids, start_time, end_time, context=None):
        """根据输入的开始和结束的时间计算出，大致的时间的间隔，（间隔可以手动修改）"""
        if start_time and end_time:
            start_time = datetime.datetime.strptime(start_time, DEFAULT_SERVER_DATETIME_FORMAT)
            end_time = datetime.datetime.strptime(end_time, DEFAULT_SERVER_DATETIME_FORMAT)
            if not ids:
                apply_seconds = (end_time - start_time).total_seconds()
                return {'value': {
                        'hour_qty': round(apply_seconds/(60*60), 1)}}

    
    def _get_leave_work_date(self, cr, uid, ids, name, args, context=None):
        """根据开时间得出开始的日期（精确到天）"""
        res = {}
        for leave_row in self.browse(cr, uid, ids, context=context):
            res[leave_row.id] = leave_row.start_time and leave_row.start_time[:10]
        return res
    
    def reject_work_overtime(self, cr, uid, ids ,context=None):
        """驳回 请假（已审批的）调休记录"""
        reconcile_obj = self.pool.get('work.time.reconcile')
        for work_leave_row in self.browse(cr, uid, ids, context=context):
            if work_leave_row.type in ('overtime', 'annual_leave') and work_leave_row.is_approve\
                    and work_leave_row.hour_qty != work_leave_row.residue_qty:
                reconcile_ids = reconcile_obj.search(cr, uid, [('ol_id', '=', work_leave_row.id)], context=context)
                err_messge = u'本条请假已被调休占用！请删除占用调休后再进行操作！\n 占用详情'
                for reconcile_row in reconcile_obj.browse(cr, uid, reconcile_ids, context=context):
                    if reconcile_row.reconcile_id:
                        err_messge += u'日期[%s]调休%s'%(reconcile_row.reconcile_id.ol_id.start_time[:10],
                                                       reconcile_row.reconcile_id.ol_id.hour_qty)
                raise osv.except_osv(u'错误', err_messge)
            work_leave_row.write({'is_approve': False, 'is_refuse': False})
        return True
    
    _columns = {
        'user_id': fields.many2one('res.users', string='申请人'),
        'employee_id': fields.many2one('hr.employee', string='申请员工'),
        'type': fields.selection([('changeworkday', u'调休'), ('overtime', u'加班'), ('annual_leave', u'年假')], string='申请类型'),
        'date': fields.date(string=u'日期'),
        'start_time': fields.datetime(u'开始时间', required=True ),
        'end_time': fields.datetime(u'结束时间', required=True),
        'hour_qty': fields.float(u'申请小时数', digits_compute=dp.get_precision('Hours')),
        'residue_qty': fields.function(_compute_residue_qty, type='float', string=u'剩余小时数',
                                       digits_compute=dp.get_precision('Hours'),
                                       store={'work.time.reconcile': (_get_leave_work_ids,
                                                                      ['hour_qty', 'reconcile_id'], 10),
                                              'work.overtime.leave': (lambda self, cr, uid, ids, c={}: ids,
                                                            ['hour_qty'], 10)
                                              },
                                       fnct_search=_residue_fnct_search,
                                       ),
        'approver_user_id': fields.many2one('res.users', string='审批人'),
        'approve_time': fields.datetime(u'审批时间'),
        'is_approve': fields.boolean(u'是否审批通过'),
        'note': fields.text(u'备注'),
        'reconcile_text': fields.text(u'调休详情'),
        'reconcile_ids': fields.many2many('work.overtime.leave', 'work_overtime_leave_ref',
                                          'overtime_id', 'leave_id', string='调休详情'),
        'is_refuse': fields.boolean(u'拒绝'),
        'punch_in_time_id': fields.many2one('weixin.punch', u'上班打卡时间'),
        'punch_out_time_id': fields.many2one('weixin.punch', u'下班打卡时间'),
        'expire_date': fields.date(u'过期时间'),
        'age': fields.integer(u'年份'),
    }

    def write(self, cr, uid, ids, vals, context=None):
        return_val = super(work_overtime_leave, self).write(cr, uid, ids, vals, context=context)
        reconcile_obj = self.pool.get('work.time.reconcile')
        for work_row in self.browse(cr, uid, ids, context=context):
            if vals.get('hour_qty') and not work_row.is_approve and work_row.type == 'changeworkday':
                if vals.get('hour_qty')*2.0 % 1 != 0:
                    raise osv.except_osv(u'错误', u"调戏时间必须为0.5小时的整数倍!")
                reconcile_ids = reconcile_obj.search(cr, uid, [('ol_id', '=', work_row.id)], context=context)
                reconciled_ids = reconcile_obj.search(cr, uid, [('reconcile_id', 'in', reconcile_ids)], context=context)
                reconcile_obj.write(cr, uid, reconciled_ids, {'reconcile_id': False}, context=context)
                reconcile_obj.unlink(cr, uid, reconcile_ids, context=context)
                self.create_reconcile_and_reconciled(cr, uid,
                                                     {'hour_qty': vals.get('hour_qty'),
                                                      'type': work_row.type,
                                                      'reconcile_ids':
                                                          [(False, False, [reconcile_id.id for
                                                                           reconcile_id in work_row.reconcile_ids])]},
                                                     work_row, context=context)
                vals.update({'is_refuse': False})
            elif vals.get('hour_qty') and work_row.is_approve:
                raise osv.except_osv(u'错误', u"已审核不能进行修改!")
        if return_val:
            return ids
        raise osv.except_osv(u'错误', u"修改出错！")

    def approve_refuse(self, cr, uid, ids, context=None):
        """ 拒绝请假，调休单 。并发送同志给员工"""
        work_leave_row = self.browse(cr, uid, ids, context=context)
        if work_leave_row.approver_user_id.id != uid:
            raise osv.except_osv(u'错误', u"您不是本张单据的审批人!")
        work_leave_row.write({'is_refuse': True})
        reconcile_obj = self.pool.get('work.time.reconcile')
        reconcile_ids = reconcile_obj.search(cr, uid, [('reconcile_id.ol_id', '=', ids)], order='create_date',
                                             context=context)
        if reconcile_ids:
            reconcile_obj.write(cr, uid, reconcile_ids, {'reconcile_id': False}, context=context)
        send_message = u"<a href=\"http://%s/wx/hr/%s/all\">您在%s申请的%s%s小时被拒绝，请重新申请！</a>" % (
            request.httprequest.host,
            type_http.get(work_leave_row.type),
            work_leave_row.create_date,
            type_dict.get(work_leave_row.type),
            work_leave_row.hour_qty,
        )
        self.pool.get('sale.order').send_wexin_message(cr, SUPERUSER_ID,
                                                 work_leave_row.user_id.id,
                                         send_message, context=context)
        return True

    def send_message_to_approve(self, cr, uid, ids, context=None):
        # type_dict = dict([('changeworkday', u'调休'), ('overtime', u'加班')])
        # type_http = dict([('changeworkday', 'leave'), ('overtime', 'work')])
        # for work_leave_row in self.browse(cr, uid, ids, context=context):
        #     send_message = u"<a href=\"http://%s/wx/hr/%s/unapprove\">您部门员工%s，申请%s%s%s小时请及时审批</a>"%(
        #         request.httprequest.host,
        #         type_http.get(work_leave_row.type),
        #         work_leave_row.user_id.name,
        #         work_leave_row.start_time and work_leave_row.start_time[:10],
        #         type_dict.get(work_leave_row.type),
        #         work_leave_row.hour_qty,
        #     )
        #     self.pool.get('sale.order').send_message(cr, SUPERUSER_ID,
        #                                              work_leave_row.approver_user_id.id,
        #                                              send_message, context=context)
        return True

    def unlink(self, cr, uid, ids, context=None):
        reconcile_obj = self.pool.get('work.time.reconcile')
        for leave in self.browse(cr, uid, ids, context=context):
            if leave.is_approve:
                raise osv.except_osv(u'错误', u"已审批不能删除!")
            else:
                reconcile_ids = reconcile_obj.search(cr, uid, [('ol_id', '=', leave.id)], context=context)
                reconciled_ids = reconcile_obj.search(cr, uid, [('reconcile_id', 'in', reconcile_ids)], context=context)
                reconcile_obj.write(cr, uid, reconciled_ids, {'reconcile_id': False}, context=context)
                reconcile_obj.unlink(cr, uid, reconcile_ids, context=context)
        return super(work_overtime_leave, self).unlink(cr, uid, ids, context=context)

    def approve_agree(self, cr, uid, ids, context=None):
        """审批通过用户的请假，或者调休的单据"""
        for leave in self.browse(cr, uid, ids, context=context):
            if leave.approver_user_id.id != uid:
                raise osv.except_osv(u'错误', u"您不是本张单据的审批人!")
            send_message = u"<a href=\"http://%s/wx/hr/%s/all\">您在%s申请的%s%s小时已经审批通过了！</a>" % (
                request.httprequest.host,
                type_http.get(leave.type),
                leave.create_date,
                type_dict.get(leave.type),
                leave.hour_qty,
            )
            self.pool.get('sale.order').send_wexin_message(cr, SUPERUSER_ID,
                                                           leave.user_id.id,
                                                           send_message, context=context)
            self.write(cr, uid, leave.id, {'is_approve': True,
                                           'approve_time': datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')},
                       context=context)
        return True
    
    def add_punch_date(self, cr, uid, vals, context=None):
        """如果打卡记录存在，在新建，请假调休记录时，"""
        weixin_uid = self.pool.get('weixin.contacts').search(cr, SUPERUSER_ID, [('odoo_user_id', '=', uid)], context=context)
        return_vals = {}
        date_str = vals.get('start_time') and vals.get('start_time')[:10] or False
        punch_ids = self.pool.get('weixin.punch').search(cr, SUPERUSER_ID, [('userid', '=', weixin_uid and weixin_uid[0]),
                                                                            ('date', '>=', "%s 00:00:00" % date_str),
                                                                            ('date', '<', '%s 23:59:59' % date_str)],
                                                         context=context)
        for punch in self.pool.get('weixin.punch').browse(cr, SUPERUSER_ID, punch_ids, context=context):
            if punch.checkin_type == u'上班打卡':
                return_vals.update({'punch_in_time_id': punch.id})
            elif punch.checkin_type == u'下班打卡':
                return_vals.update({'punch_out_time_id': punch.id})
        return return_vals
    
    def create(self, cr, uid, vals, context=None):
        """创建请假调休记录， 存在打卡记录的情况下，要关联，请假调休记录"""
        if self.check_time_have_repeat(cr, uid, vals, context=context):
            raise osv.except_osv(u'错误', u'申请时间段重叠或者部分重叠!')
        if not vals.get('start_time', False):
            raise osv.except_osv(u'错误', u'请填写开始时间!')
        date_str = vals.get('start_time') and vals.get('start_time')[:10] or False
        vals.update({'date': date_str})
        if vals.get('type') == 'overtime':
            vals.update(self.add_punch_date(cr, uid, vals, context=context))
            vals.update(
                {'expire_date': (datetime.datetime.strptime(vals.get('start_time'), ISODATETIMEFORMAT) +
                                 relativedelta(years=1)).strftime(ISODATEFORMAT)})
        elif vals.get('type') == 'changeworkday' and float_compare(vals.get('hour_qty'), 0.5, precision_digits=1) < 0:
            raise osv.except_osv(u'错误', u"调休时间必须大于0.5小时!")
        over_time_id = super(work_overtime_leave, self).create(cr, uid, vals, context=context)
        over_time_row = self.browse(cr, uid, over_time_id, context=context)
        all_hours = sum([work_leave_row.residue_qty for work_leave_row
                         in over_time_row.reconcile_ids])
        if over_time_row.reconcile_ids and (not all_hours or over_time_row.hour_qty > all_hours):
            raise osv.except_osv(u'错误', u'调休的小时数不能大于调休详情中的总小时数!')
        return_create_reconcile = self.create_reconcile_and_reconciled(cr, uid, vals, over_time_row, context=context)
        return_approve = self.send_message_to_approve(cr, uid, over_time_id, context=context)
        if return_create_reconcile and return_approve:
            return over_time_id
        else:
            raise osv.except_osv(u'错误', u'致命错误，新建失败!')

    def create_reconcile_and_reconciled(self, cr, uid, vals, over_time_row, context=None):
        reconcile_dict = {'ol_id': over_time_row.id}
        reconcile_dict.update({'hour_qty': round(vals.get('hour_qty'), 1)})
        reconcile_id = self.pool.get('work.time.reconcile').create(cr, uid, reconcile_dict, context=context)
        if vals.get('type') == 'changeworkday':
            reconcile_text = self.leave_reconcile(cr, uid, reconcile_id,
                                                  vals.get('reconcile_ids')[0] and
                                                  vals.get('reconcile_ids')[0][2] and
                                                  vals.get('reconcile_ids')[0][2],
                                                  vals.get('hour_qty'), context=context)
            return over_time_row.write({'reconcile_text': reconcile_text})
        else:
            return True

    def check_time_have_repeat(self, cr, uid, vals, context=None):
        """检查本时间段， 是否存在请假调休记录，目的是，避免重复提交"""
        leave_ids = self.search(cr, uid, [('user_id', '=', vals.get('user_id')),
                                          ('type', '=', vals.get('type')),
                                          '|','|','&', ('start_time', '<=', vals.get('start_time')),
                                          ('end_time', '>', vals.get('start_time')),
                                          '&', ('start_time', '<', vals.get('end_time')),
                                          ('end_time', '>=', vals.get('end_time')),
                                          '&', ('start_time', '>', vals.get('start_time')),
                                          ('end_time', '<', vals.get('end_time')),
                                          ('id', '!=', vals.get('id'))
                                          ], context=context)
        if leave_ids and vals.get('type') !='annual_leave':
            return True
        else:
            return False
        
    def onchange_reconcile_ids(self, cr, uid, ids, reconcile_ids, context=None):
        """当改变可调休的记录时。本次调休时间的上限就进一步的提高。"""
        if reconcile_ids and reconcile_ids[0] and reconcile_ids[0][0] == 6:
            all_hours = sum([work_leeave_row.residue_qty for work_leeave_row
                             in self.browse(cr, uid, reconcile_ids[0][2], context=context)])
            return {'value': {'hour_qty': round(all_hours, 1)}}

    def leave_reconcile(self, cr, uid, reconcile_id, work_leave_ids, hour_qty, context=None):
        """核销请假调休记录(类似与财务的核销)"""
        reconcile_obj = self.pool.get('work.time.reconcile')
        overplus_text, change_work, overplus_qty = '', False, 0
        reconcile_ids = reconcile_obj.search(cr, uid, ['&', ('ol_id', 'in', work_leave_ids),
                                                       ('ol_id.type', '=', 'overtime'),
                                                       ('reconcile_id', '=', False)], order='create_date', context=context)
        annual_reconcile_ids = reconcile_obj.search(cr, uid, ['&', ('ol_id', 'in', work_leave_ids),
                                                              ('ol_id.type', '=', 'annual_leave'),
                                                              ('reconcile_id', '=', False)], order='create_date',
                                                    context=context)
        annual_reconcile_all_hours = sum([annual.hour_qty for annual
                                          in reconcile_obj.browse(cr, uid, annual_reconcile_ids, context=context)])
        if float_compare(hour_qty / 8, 1, precision_digits=1) >= 0 and annual_reconcile_ids \
            or annual_reconcile_all_hours < 8:
            reconcile_hour_qty = (hour_qty // 8) * 8
            if not reconcile_hour_qty:
                reconcile_hour_qty = hour_qty
            overplus_text, overplus_qty = self.reconcile_hour_qty(cr, uid, reconcile_hour_qty, annual_reconcile_ids, reconcile_id, context=context)
            if reconcile_hour_qty >= 8:
                hour_qty = hour_qty % 8 + overplus_qty
            else:
                hour_qty = overplus_qty
        reconcile_text, hour_qty = self.reconcile_hour_qty(cr, uid,  hour_qty, reconcile_ids, reconcile_id, context=context)
        if hour_qty and (not annual_reconcile_ids or overplus_qty != 0):
            raise osv.except_osv(u'错误', u'可用调休数量不够!')
        elif annual_reconcile_ids and hour_qty:
            raise osv.except_osv(u'错误', u'年假调休时间以8小时为单位!')
        return reconcile_text + overplus_text

    def reconcile_hour_qty(self, cr, uid, hour_qty, reconcile_ids, reconcile_id, context=None):
        reconcile_obj = self.pool.get('work.time.reconcile')
        reconcile_text = ''
        for reconcile_row in reconcile_obj.browse(cr, uid, reconcile_ids, context=context):
            reconcile_text += '%s[%s]%s' % (type_dict.get(reconcile_row.ol_id.type),
            reconcile_row.ol_id.start_time and reconcile_row.ol_id.start_time[:10], reconcile_row.hour_qty if
                                            float_compare(hour_qty, reconcile_row.hour_qty, precision_digits=1) >= 0 else hour_qty)
            hour_qty = hour_qty - reconcile_row.hour_qty
            if float_compare(hour_qty, 0, precision_digits=1) > 0:
                reconcile_row.write({'reconcile_id': reconcile_id})
                if reconcile_row.ol_id.expire_date < reconcile_row.reconcile_id.ol_id.start_time or \
                                reconcile_row.ol_id.expire_date < reconcile_row.reconcile_id.ol_id.end_time:
                    raise osv.except_osv(u'错误', u'部分加班已过期过期时间(调休开始或者结束时间大于加班/年假的过期时间)!')
            else:
                if not float_is_zero(hour_qty, precision_digits=1):
                    reconcile_obj.create(cr, uid, {'ol_id': reconcile_row.ol_id.id,
                                                   'hour_qty': round(-hour_qty, 1)}, context=context)
                reconcile_row.write({'hour_qty': round(reconcile_row.hour_qty + hour_qty, 1),
                                     'reconcile_id': reconcile_id})
                hour_qty = 0
                if reconcile_row.ol_id.expire_date < reconcile_row.reconcile_id.ol_id.start_time or \
                                reconcile_row.ol_id.expire_date < reconcile_row.reconcile_id.ol_id.end_time:
                    raise osv.except_osv(u'错误', u'部分加班已过期过期时间(调休开始或者结束时间大于加班/年假的过期时间)!')
                break
        return reconcile_text, round(hour_qty, 2)

    def name_get(self, cr, uid, ids, context=None):
        """ name_get方法 是为了 方便的识别此条记录所属的  """
        res = []
        for overtime in self.browse(cr, uid, ids, context=context):
            if overtime.type == 'overtime':
                res.append((overtime.id, "加班(%s／%s小时)" % (overtime.residue_qty, overtime.hour_qty)))
            elif overtime.type == 'annual_leave':
                res.append((overtime.id, "年假(%s／%s小时)" % (overtime.residue_qty, overtime.hour_qty)))
            else:
                res.append((overtime.id, "[%s]%s(小时)" % (overtime.start_time and
                                                           overtime.start_time[:10], overtime.residue_qty)))
        return res

    _defaults = {
        'user_id': lambda self, cr, uid, context=None: uid,
    }
    

class work_time_reconcile(osv.osv):
    _name = 'work.time.reconcile'

    def _get_reconcile_id_date(self, cr, uid, ids, name, args, context=None):
        res = {}
        for id in ids:
            res[id] = {'start_time': '', 'end_time': ''}
        for reconcile in self.browse(cr, uid, ids, context=context):
            if reconcile.reconcile_id and reconcile.reconcile_id.ol_id:
                res[reconcile.id]['start_time'] = reconcile.reconcile_id.ol_id.start_time or False
                res[reconcile.id]['end_time'] = reconcile.reconcile_id.ol_id.end_time or False
            else:
                res[reconcile.id]['start_time'] = False
                res[reconcile.id]['end_time'] = False
        return res

    _columns = {
        'user_id': fields.related('ol_id', 'user_id', type='many2one', relation='res.users', store=True, string='申请人'),
        'ol_id': fields.many2one('work.overtime.leave', u'加班／年假', ondelete='cascade'),
        'type': fields.related('ol_id', 'type',  type='selection', store=True,
                               selection =[('changeworkday', u'调休'), ('overtime', u'加班'), ('annual_leave', u'年假')],
                               string='使用类型'),
        'origin_ol_id': fields.related('reconcile_id', 'ol_id', type='many2one', store=True,
                                       relation='work.overtime.leave', string='调休记录'),
        'start_time': fields.function(_get_reconcile_id_date, type='datetime', store=True, multi="reconcile_date", string='开始时间'),
        'end_time': fields.function(_get_reconcile_id_date, type='datetime', store=True, multi="reconcile_date", string='结束时间'),
        'hour_qty': fields.float(u'小时数'),
        'reconcile_id': fields.many2one('work.time.reconcile', u'核销编号'),
    }


class weixin_punch(osv.osv):
    _name = 'weixin.punch'
    _rec_name = 'date'
    
    def name_get(self, cr, user, ids, context=None):
        """根据不同的情况 进行分类的 显示prodcut的name """
        res = [(punch.id, time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(int(punch.checkin_time)+28800)))
                for punch in self.browse(cr, user, ids, context=context)]
        return res
    
    _columns = {
        'checkin_time': fields.char(u'打卡时间'),
        'checkin_type': fields.char(u'打卡类型'),
        'exception_type': fields.char(u'异常类型'),
        'groupname': fields.char(u'组名'),
        'userid': fields.many2one('weixin.contacts', string='微信联系人'),
        'notes': fields.text(u'说明'),
        'wifimac': fields.char(u'wifi设备mac地址'),
        'location_title': fields.text(u'打卡地址简称'),
        'location_detail': fields.text(u'打卡详细地址'),
        'wifiname': fields.char(u'wifi名字'),
        'mediaids': fields.char(u'附件'),
        'date': fields.datetime(u'日期'),
    }


class weixin_punch_rule(osv.osv):
    _name = 'weixin.punch.rule'
    _columns = {
        'name': fields.char(u'打卡规则名称'),
        'begin_datetime': fields.char(u'打卡开始时间'),
        'end_datetime': fields.char(u'打卡结束时间'),
    }


class annual_leave_days_rule(osv.osv):
    _name = 'annual.leave.days.rule'

    _columns = {
        'min_year': fields.integer(u'最小年份'),
        'max_year': fields.integer(u'最大年份'),
        'annual_days': fields.integer(u'年假天数')
    }